package cn.fancylab.template.web.action.admin;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jivesoftware.smack.packet.Message;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.ModelAndView;

import cn.fancylab.model.acl.AuthUser;
import cn.fancylab.util.DateUtil;
import cn.fancylab.util.JsonUtils;
import cn.fancylab.util.ObjectId;
import cn.fancylab.web.support.FancyDeferredResult;
import cn.fancylab.xmpp.magent.WebContainerMonitorAgent;

@Controller
public class DeviceAdminController extends BaseAdminController implements InitializingBean{
	@Autowired
	private WebContainerMonitorAgent monitorAgent;
	/**
	 * 修改相机信息
	 */
	@RequestMapping("/admin/sendCommond.xhtml")
	public DeferredResult<ModelAndView> sendCommond(String deviceId) {
		AuthUser user = getLogonUser();
		//1. getDevice :gtResultCode<Camera> resultCode = cameraService.saveCamera(requestMap, user.getId());
		//
		String domain = "myxmpp.server.com"; /*FIXME: openfire domain*/
		deviceId = "myDevice1";
		String callbackKey = "restart" + System.currentTimeMillis();
		String command = "restart device";
		
		FancyDeferredResult result = getFancyDeferredResult();
		monitorAgent.getClient().sendMsg(deviceId + "@" + domain, command, callbackKey, (Message message)-> {
			String reply = message.getBody();
			dbLogger.warn("reload remote config:" + reply);
			result.setDirectStr("return:" + reply);
			return null;
		});
		return result;
	}
	/**
	 * 上报磁盘空间，网速等
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void afterPropertiesSet() throws Exception {
		monitorAgent.getClient().registerFixedCallback((message)->{
			String subject = message.getSubject();
			//注册监听事件，接收消息
			if(StringUtils.equals(subject, "camera_report")) {
				String msg = message.getBody();
				dbLogger.warn(msg);
				Map data = JsonUtils.readJsonToMap(msg);
				Map report = new HashMap();
				report.put("_id", data.get("mac"));
				report.put("runtimes", data);
				report.put("status", "work");
				data.put("_id", ObjectId.uuid());
				data.put("timestamp", DateUtil.getCurFullTimestampStr());
				//TODO
			}
			return null;
		});
		
	}
}
